﻿using System;
using System.Linq;
using Windows.Phone.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using FunstreamTV.Common;
using FunstreamTV.Model.Category;
using FunstreamTV.Tools;
using FunstreamTV.ViewModel;
using FunstreamTV.ViewModel.ObjectViewModel;

namespace FunstreamTV
{
    public sealed partial class ClientPage
    {
        private NavigationHelper navigationHelper;
        public ClientViewModel ClientViewModel { get; set; }

        public ClientPage()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            HardwareButtons.BackPressed += HardwareButtons_BackPressed;
        }

        private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
        {
            Application.Current.Exit();
        }
        public NavigationHelper NavigationHelper => navigationHelper;

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            DataContext = new ClientViewModel();
            ClientViewModel = (ClientViewModel)DataContext;

            await ClientViewModel.Load();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
            HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
        }

        private async void RefreshClick(object sender, RoutedEventArgs e)
        {
            await ClientViewModel.Load();
        }

        private void StreamClick(object sender, ItemClickEventArgs e)
        {
            var content = (e.ClickedItem as ContentViewModel);
            if (content != null)
                Frame.Navigate(typeof(StreamPage), content);
        }

        private async void CategoryClick(object sender, ItemClickEventArgs e)
        {
            var category = e.ClickedItem as Category;
            if (category?.id != null)
                await ClientViewModel.LoadSubcategory(category.id.Value);
        }

        private async void ResetCategory(object sender, RoutedEventArgs e)
        {
            await ClientViewModel.LoadSubcategory(0);
        }

        private void PivotItemSelected(object sender, SelectionChangedEventArgs e)
        {
            ClientViewModel.GoBackAppButtonVisibility = (sender as Pivot).SelectedIndex == 2 ? Visibility.Visible : Visibility.Collapsed;
        }

        private async void LogoutClick(object sender, RoutedEventArgs e)
        {
            await FileManager.Remove("LoginResponse");
            Frame.Navigate(typeof (MainPage));
        }
    }
}
